import { defineStore } from 'pinia'
import { ref } from 'vue'
import { CaseDTO, CaseQueryDTO, CaseAuditDTO, getCasePage, getCaseDetail, createCase, updateCase, deleteCase, submitCase, publishCase, unpublishCase, auditCase, getCaseTypes } from '@/api/kg/case'
import { ElMessage } from 'element-plus'

export const useCaseStore = defineStore('case', () => {
  // 加载状态
  const loading = ref(false)
  // 案例列表
  const caseList = ref<CaseDTO[]>([])
  // 总条数
  const total = ref(0)
  // 当前页
  const currentPage = ref(1)
  // 每页大小
  const pageSize = ref(12)

  // 查询参数
  const queryParams = ref<CaseQueryDTO>({
    page: 1,
    size: 12
  })

  // 表单数据
  const formData = ref<CaseDTO>({
    nodeId: undefined,
    name: '',
    description: '',
    cover: '',
    type: '',
    difficulty: 1,
    status: 0
  })

  // 案例类型列表
  const caseTypes = ref<string[]>([])

  // 表单弹窗可见性
  const formVisible = ref(false)
  // 表单类型：新增/编辑
  const formType = ref<'add' | 'edit'>('add')

  // 获取案例列表
  const fetchCaseList = async () => {
    loading.value = true
    try {
      const res = await getCasePage({
        ...queryParams.value,
        page: currentPage.value - 1, // 后端页码从0开始
        size: pageSize.value,
        // 确保name字段有值
        name: queryParams.value.name || undefined,
        // 确保type字段格式正确
        type: Array.isArray(queryParams.value.type)
          ? String(queryParams.value.type[0] || '')
          : queryParams.value.type
      })

      // 处理返回的数据
      if (res && res.data) {
        caseList.value = (res.data.content || []).map(item => ({
          ...item,
          // 确保类型是字符串而不是数组
          type: Array.isArray(item.type) ? String(item.type[0] || '未分类') : String(item.type || '未分类')
        }))
        total.value = res.data.totalElements || 0
      } else {
        caseList.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('获取案例列表失败:', error)
      ElMessage.error('获取案例列表失败')
      caseList.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 获取案例类型列表
  const fetchCaseTypes = async () => {
    try {
      const res = await getCaseTypes()
      // 处理返回的数据结构，确保每个类型都是字符串
      const types = res.data || res;

      // 确保每个类型都是字符串
      caseTypes.value = types.map(type => {
        // 如果类型是数组，取第一个元素
        if (Array.isArray(type)) {
          return String(type[0] || '未分类')
        }
        return String(type || '未分类')
      })
    } catch (error) {
      console.error('获取案例类型失败:', error)
      ElMessage.error('获取案例类型失败')
      caseTypes.value = []
    }
  }

  // 保存案例
  const saveCase = async () => {
    loading.value = true
    try {
      // 确保提交数据格式正确
      const submitData = {
        ...formData.value,
        // 确保类型是字符串，而不是数组
        type: Array.isArray(formData.value.type)
          ? String(formData.value.type[0] || '')
          : String(formData.value.type || '')
      }

      let result;
      if (formType.value === 'add') {
        result = await createCase(submitData)
      } else {
        result = await updateCase(submitData)
      }

      formVisible.value = false
      // 关闭弹窗后清空表单数据
      resetForm()
      await fetchCaseList()
      return result
    } catch (error) {
      console.error('保存案例失败:', error)
      ElMessage.error('保存案例失败')
      return null
    } finally {
      loading.value = false
    }
  }

  // 删除案例
  const removeCase = async (nodeId: string) => {
    loading.value = true
    try {
      const res = await deleteCase(nodeId)
      if (res && res.code === 200) {
        ElMessage.success('删除案例成功')
        await fetchCaseList()
      } else {
        ElMessage.error(res?.message || '删除案例失败')
      }
    } catch (error) {
      console.error('删除案例失败:', error)
      ElMessage.error('删除案例失败')
    } finally {
      loading.value = false
    }
  }

  // 提交案例审核
  const submitCaseForReview = async (nodeId: string) => {
    loading.value = true
    try {
      const res = await submitCase(nodeId)
      if (res && res.code === 200) {
        ElMessage.success('提交审核成功')
        await fetchCaseList()
      } else {
        ElMessage.error(res?.message || '提交审核失败')
      }
    } catch (error) {
      console.error('提交审核失败:', error)
      ElMessage.error('提交审核失败')
    } finally {
      loading.value = false
    }
  }

  // 审核案例
  const performAudit = async (nodeId: string, status: number, auditMessage?: string) => {
    loading.value = true
    try {
      // 状态2表示通过，3表示拒绝
      const auditDTO: CaseAuditDTO = {
        passed: status === 2,
        auditMessage: status === 3 ? auditMessage : undefined
      }
      const res = await auditCase(nodeId, auditDTO)
      if (res && res.code === 200) {
        const statusText = status === 2 ? '通过' : '拒绝'
        ElMessage.success(`审核${statusText}成功`)
        await fetchCaseList()
      } else {
        ElMessage.error(res?.message || '审核案例失败')
      }
    } catch (error) {
      console.error('审核案例失败:', error)
      ElMessage.error('审核案例失败')
    } finally {
      loading.value = false
    }
  }

  // 重置表单
  const resetForm = () => {
    formData.value = {
      nodeId: undefined,
      name: '',
      description: '',
      cover: '',
      type: '',
      difficulty: 1,
      status: 0
    }
  }

  // 打开新增表单
  const openAddForm = () => {
    formType.value = 'add'
    // 确保先重置表单再显示弹窗，防止残留数据
    resetForm()
    formVisible.value = true
  }

  // 打开编辑表单
  const openEditForm = (data: CaseDTO) => {
    // 确保表单字段都有默认值
    formData.value = {
      ...data,
      name: data.name || '',
      description: data.description || '',
      cover: data.cover || '',
      type: data.type || '',
      difficulty: data.difficulty || 1,
      status: data.status || 0
    }
    formType.value = 'edit'
    formVisible.value = true
  }

  return {
    loading,
    caseList,
    total,
    currentPage,
    pageSize,
    queryParams,
    formData,
    formVisible,
    formType,
    caseTypes,
    fetchCaseList,
    fetchCaseTypes,
    saveCase,
    removeCase,
    submitCaseForReview,
    performAudit,
    resetForm,
    openAddForm,
    openEditForm
  }
})
